import {
    SignJWT,
    jwtVerify
} from 'jose';
import {
    cookies
} from 'next/headers';

const getJwtSecretKey = () => {
    const secret = process.env.JWT_SECRET_KEY;
    if (!secret) {
        throw new Error('JWT_SECRET_KEY is not defined');
    }
    // 二进制的secret
    return new TextEncoder().encode(secret);
}

export const createTokens = async (userId: number) => {
    const accessToken = await new SignJWT({
        // 创建JWT 载荷
        userId
    }).setProtectedHeader({
        // 设置头部，指定使用HS256算法签名
        alg: 'HS256'
    })
        // 颁发的时间 当前时间
        .setIssuedAt()
        // 过期时间 15m
        .setExpirationTime('15m')
        // 使用secret签名
        .sign(getJwtSecretKey())

    const refreshToken = await new SignJWT({
        userId
    })
        .setProtectedHeader({
            alg: 'HS256'
        })
        .setIssuedAt()
        .setExpirationTime('7d')
        .sign(getJwtSecretKey());

    return {
        accessToken,
        refreshToken
    }
}

export const setAuthCookies = async (accessToken: string, refreshToken: string) => {
    // 响应头设置cookie
    const cookieStore = await cookies();
    cookieStore.set('accessToken', accessToken, {
        // 黑客XSS 攻击 js  试图获得cookie
        httpOnly: true, // 不能用javascript 操作cookie
        sameSite: 'strict',
        path: '/',
        maxAge: 15 * 60
    })
    cookieStore.set('refreshToken', refreshToken, {
        httpOnly: true,
        sameSite: 'strict',
        path: '/',
        maxAge: 7 * 24 * 60 * 60
    })
}

export const verifyToken = async (token: string) => {
    try {
        const {
            payload
        } = await jwtVerify(token, getJwtSecretKey());
        return payload;
    } catch (error) {
        return null;
    }
}
